package com.imooc.controller;

import com.imooc.bo.UserBo;
import com.imooc.service.UserService;
import com.imooc.pojo.Users;
import com.imooc.utils.CookieUtils;
import com.imooc.utils.IMOOCJSONResult;
import com.imooc.utils.JsonUtils;
import com.imooc.utils.MD5Utils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author wangke
 * @Description 登录注册控制器
 * @Date 2021/7/5 19:46
 * @Version 1.0
 */
@RestController
@RequestMapping("/passport")
@Api(value = "用户注册",tags = {"用户的注册与校验"})
public class PassportController {
    @Autowired
    private UserService usersService;

    @GetMapping("/usernameIsExist")
   @ApiOperation(value = "用户名校验",notes = "用户名是否重复校验",httpMethod = "GET")
    public IMOOCJSONResult queryUsernameIsExist(@RequestParam String username){
        // isBlanK除了判断 null值 还会判断空字符串情况
        if(StringUtils.isBlank(username))
            //用户名不能为空
          return IMOOCJSONResult.errorMsg("用户名不能为空");
        Boolean isExist = usersService.queryUsernameIsExist(username);

        if(isExist){
            //用户名已经存在
            return IMOOCJSONResult.errorMsg("用户名已经存在");
        }
        //用户名不存在
         return IMOOCJSONResult.ok();
    }


    @PostMapping("/regist")
    @ApiOperation(value = "用户注册保存",notes = "用户注册保存信息",httpMethod = "POST")
    public IMOOCJSONResult registerUser(@RequestBody UserBo userBo,
                                        HttpServletRequest request,
                                        HttpServletResponse response){
        //判断用户名或密码是否为null
        if(StringUtils.isBlank(userBo.getUsername())|| StringUtils.isBlank(userBo.getPassword())||StringUtils.isBlank(userBo.getConfirmPassword())){
            return IMOOCJSONResult.errorMsg("用户名或密码不能为空");
        }
        //校验用户密码是否一致
        if(!userBo.getPassword().equals(userBo.getConfirmPassword())){
            return IMOOCJSONResult.errorMsg("密码前后不一致");
        }

        //判断用户名是否已经存在
        if(usersService.queryUsernameIsExist(userBo.getUsername())){
            return IMOOCJSONResult.errorMsg("用户名已经存在，请更换!");
        }
        //判断用户密码长度
        if(userBo.getPassword().length()<6){
            return IMOOCJSONResult.errorMsg("密码长度必须超过6位!！！");
        }
        //调用服务保存注册信息
        Users user = usersService.createUser(userBo);
        //去除用户隐私信息
         user= ignoreData(user);
         //添加cookie信息
        CookieUtils.setCookie(request,response,"user",JsonUtils.objectToJson(user),true);

        //Todo 用户登录信息token的生成和redis缓存
        //Todo 同步redis用户购物车信息

        // 返回数据信息
        return IMOOCJSONResult.ok(userBo);
    }


    @PostMapping("/login")
    @ApiOperation(value = "用户登录",notes = "用户登录认证服务",httpMethod = "POST")
    public IMOOCJSONResult queryUserForLogin(@RequestBody UserBo userBo,
                                             HttpServletRequest request, HttpServletResponse response) throws Exception{
        //校验信息是否为空
        String username = userBo.getUsername();
        String password= userBo.getPassword();

        if(StringUtils.isBlank(username)|| StringUtils.isBlank(password)){
            return IMOOCJSONResult.errorMsg("用户名或密码不能为空");
        }
        Users user = usersService.QueryUserForLogin(username, MD5Utils.getMD5Str(password));
        if(user==null){
            return IMOOCJSONResult.errorMsg("用户名或密码错误！！");
        }
         user = ignoreData(user);
        //将用户信息添加到cookie,cookie 名，值，进行编码
        CookieUtils.setCookie(request,response,"user",JsonUtils.objectToJson(user),true);

        //Todo 用户登录信息token的生成和redis缓存
        //Todo 同步redis用户购物车信息

        return IMOOCJSONResult.ok(user);
    }

    //清除cookie 完成用户退出登录
    @PostMapping("/logout")
    @ApiOperation(value = "用户退出登录",notes = "用户退出登录",httpMethod = "POST")
    public IMOOCJSONResult logout(@RequestParam String userId ,HttpServletRequest request,HttpServletResponse response){
        CookieUtils.deleteCookie(request,response,"user");

        //TODO 清除用户购物车缓存
        //TODO 清除用户的登录token信息
        return IMOOCJSONResult.ok();

    }

    //处理用户数据，将用户隐私信息处理，不再返回前端
    public Users ignoreData(Users users){
        users.setPassword(null);
        users.setCreatedTime(null);
        users.setUpdatedTime(null);
        users.setRealname(null);
        users.setMobile(null);
        users.setEmail(null);
        return users;
    }


}
